package com.tiancai.service.Impl;

import com.tiancai.constant.MessageConstant;
import com.tiancai.exception.AccountNotFoundException;
import com.tiancai.exception.CustomException;
import com.tiancai.mapper.UserMapper;
import com.tiancai.mapper.UserRoleMapper;
import com.tiancai.pojo.dto.UserRegistDto;
import com.tiancai.pojo.po.User;
import com.tiancai.pojo.po.UserRole;
import com.tiancai.service.IUserRoleService;
import com.tiancai.service.MailService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class MailServiceImpl implements MailService {
        @Autowired
        private JavaMailSender mailSender;//一定要用@Autowired

        @Autowired
        private UserMapper userMapper;//注入UserMapper，交给bena

        @Autowired
        private RedisTemplate redisTemplate;
        @Autowired
        private UserRoleMapper userRoleMapper;


        //application.properties中已配置的值
        @Value("${spring.mail.username}")
        private String from;

        /**
         * 给前端输入的邮箱，发送验证码
         * @param email
         * @param session
         * @return
         */
        public void sendMimeMail( String email, HttpSession session) {
            try {
                SimpleMailMessage mailMessage = new SimpleMailMessage();

                mailMessage.setSubject("【吉里尔斯】");//主题
                //生成随机数
                String code = randomCode();

                //将随机数放置到session中
                session.setAttribute("email",email);
                session.setAttribute("code",code);

                //把code放在redis中，设置时间为一分钟
                redisTemplate.opsForValue().set("code",code,1, TimeUnit.MINUTES);
                mailMessage.setText("尊敬的用户您好，\n\n感谢您选择我们的服务！您的登录验证码为："+"["+code+"]"+"，请妥善保管。请注意，该验证码仅在三分钟内有效，请尽快使用。\n\n若有任何疑问，请随时联系我们。祝您生活愉快");//内容

                mailMessage.setTo(email);//发给谁

                mailMessage.setFrom(from);//你自己的邮箱

                mailSender.send(mailMessage);//发送
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        /**
         * 随机生成6位数的验证码
         * @return String code
         */
        public String randomCode(){
            StringBuilder str = new StringBuilder();
            Random random = new Random();
            for (int i = 0; i < 6; i++) {
                str.append(random.nextInt(10));
            }
            return str.toString();
        }

        /**
         * 检验验证码是否一致
         * @param
         * @param session
         * @return
         */
        public User registered(UserRegistDto userRegistDto, HttpSession session){

            //获取session中的验证信息
            String email = (String) session.getAttribute("email");
            String voCode = userRegistDto.getCode();
            if (email == null || email.isEmpty()){
                //return "error,请重新注册";
                throw new CustomException(MessageConstant.Email_Cannot_Be_Empty);
            }
            if (email.equals(userRegistDto.getEmail())){
                //查询数据库，看该邮箱是否已经注册
                User user = userMapper.getByUserEmail(email);
                if (user != null){
                    throw new CustomException(MessageConstant.ALREADY_EXISTS);
                }
            }

            // String code = (String) session.getAttribute("code");
            //获取表单中的提交的验证信息
            //从redis中读取code
            String code = (String) redisTemplate.opsForValue().get("code");

            if (code == null) {
                throw new CustomException(MessageConstant.Verification_Code_Expired);
            }

            if (!code.equals(voCode)) {
                throw new CustomException(MessageConstant.Verification_Code_Error);
            }

            //保存数据
            User user = new User();
            //设置code用uuid
            BeanUtils.copyProperties(userRegistDto,user);
            user.setCode(UUID.randomUUID().toString());
            //将数据写入数据库
            userMapper.insert(user);
            UserRole userRole = UserRole.builder()
                    .userId(user.getId())
                    .role("common")
                    .build();
            userRoleMapper.insert(userRole);
            return user;

        }



}
